from pathlib import Path

from PySide6.QtWidgets import QFileDialog, QWidget
from config import CONFIG_JSON
from tools import JsonEditor


class OpenFileDialog:
    def __init__(self, parent: QWidget = None):
        self.parent = parent
        self.jsonEdit = JsonEditor(CONFIG_JSON)
        self.openFile = self.jsonEdit.get('OpenFile')
        if self.openFile is None:
            self.openFile = ''

    def getExistingDirectory(self):
        file = QFileDialog.getExistingDirectory(self.parent, '选择文件夹', self.openFile)
        self.jsonEdit.setItem('OpenFile', file)
        return file

    def getOpenFileName(self, *args, filter='所有文件(*.*);'):
        file = QFileDialog.getOpenFileName(self.parent, '选择文件', self.openFile, filter)
        if file[0] != '':
            self.jsonEdit.setItem('OpenFile', str(Path(file[0]).resolve().parent))
        return file

    def getOpenFileNames(self, *args, filter='所有文件(*.*);'):
        file = QFileDialog.getOpenFileNames(self.parent, '选择多个文件', self.openFile, filter)
        if len(file[0]) > 0:
            self.jsonEdit.setItem('OpenFile', str(Path(file[0][0]).resolve().parent))
        return file

    def getSaveFileName(self, _dir: str, filter: str = '所有文件(*.*);'):
        path = Path(self.openFile) / Path(_dir).resolve().name
        file = QFileDialog.getSaveFileName(self.parent, '保存文件', dir=str(path), filter=filter)
        return file
